package com.beiyou.orderingsystemonweb.system.controller;

import com.beiyou.orderingsystemonweb.system.service.LoginService;
import com.beiyou.orderingsystemonweb.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 用户注册
 */
@Controller
public class RegisterController {
    @Autowired
    LoginService loginService;
    @Autowired
    UserService userService;
    @RequestMapping("/register.do")
    public String register(HttpServletRequest request){
        //跳转到注册页面
//        添加验证码
        //并不是在页面加载完成之后js处理
        String imgPath = request.getServletContext().getRealPath("/") + "statics/images/code/";
        Map map = addCodeImg(imgPath);
        request.setAttribute("codeImgName",map.get("codeImgName"));
        request.setAttribute("imgValue",map.get("imgValue"));
        request.setAttribute("imgPath",imgPath);
        return "/register";
    }

    @RequestMapping(value = "/goRegister.do",method = {RequestMethod.POST})
    public String goRegister(String acc,String pwd,String name, HttpServletRequest request){
        //非空判断
        if(acc==null||pwd==null||name==null){
            request.setAttribute("registerMsg","请重试");
            return "forward:/register.do";
        }
        //用户名唯一检查
        Map map = loginService.queryAcc(acc);
        if (map.get("acc")!=null){
            request.setAttribute("msg","用户名已使用");
        }else{
            //密码加密

            userService.register(acc,pwd,name,1);
            //post请求可以不显示到地址栏,转发到登录
            request.setAttribute("msg","注册成功，请登录");
            request.setAttribute("loginAcc",acc);
            request.setAttribute("loginPwd",pwd);
            return "/login";
        }
        return "/register";
    }

    //用户名唯一检查
    @ResponseBody
    @RequestMapping("/oneAcc.data")
    public Map oneAcc(String acc){
        if (acc!=null&&!"".equals(acc)){
            Map map = loginService.queryAcc(acc);
//            map.put("nullFlag",new Object());
            map.put("nullFlag","");
            return map;
        }
        return null;
    }

    //动态验证码生成
    @RequestMapping("/codeImg.data")
    @ResponseBody
    public Map addCodeImg(String imgUri){
        if (imgUri!=null){
            String letter = "abcdefghijklmnopqrstuvwsyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            int imgWidth = 160;
            int imgHeight = 60;
            int len= 4;
            //imgType选择的是彩色可选透明的 2  1（RGB） 10(灰度)
            BufferedImage img = new BufferedImage(160,60,2);
            Graphics2D pen = img.createGraphics();
            FontMetrics metrics = pen.getFontMetrics();
            int sh = metrics.getAscent();
            String text;
            int width = imgWidth/len;
            pen.setFont(new Font("",1,30));
            //一次写一个，位置，大小可以控制
            //动态拼接
            StringBuilder context = new StringBuilder();
            for (int i = 0,x = 20;i<len;i++){
                int y = (int)(Math.random()*(imgHeight-sh)) + sh +5;
                text = String.valueOf( letter.charAt((int)(Math.random()*62)));
                context.append(text);
                pen.setColor(new Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*100)+100));
                pen.drawString(text,x,y);
                x+=width;
            }
            //添加干扰
            int l = 50;
            for (int i = 0,x,y;i<l;i++){
                x = (int)(Math.random()*(imgWidth));
                y = (int)(Math.random()*(imgHeight));
                text = String.valueOf( letter.charAt((int)(Math.random()*62)));
                pen.setColor(new Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*50)));
                pen.setFont(new Font("楷体",2,(int)(Math.random()*20)));
                pen.drawString(text,x,y);
            }
            //添加正弦干扰线,弯曲的线
            //在字体后面添加会覆盖字体，增加识别难度
            //斜率不同 根据图片高度控制这里0-1合适
            boolean flag = true;
            pen.setColor(new Color(12,50,12,10));
            pen.setStroke(new BasicStroke(5f));
            for (int x=0,y = imgHeight/2,k;x<imgWidth;){
                k = (int)(Math.random()*(2));
                if (flag){
                    pen.drawLine(x,y,x+1,y-=k);
                    y-=2*k;
                    if (y<imgHeight/4){
                        flag = false;
                    }
                }
                else{
                    pen.drawLine(x,y,x+1,y+=k);
                    y+=2*k;
                    if (y>imgHeight/4 *3){
                        flag = true;
                    }
                }
                x+=2;
            }
            try {
                //图片保存地址 --绝对地址 --
                Map<String,String> map = new HashMap<>(2);
                String imgccc = UUID.randomUUID().toString().replace("-","") +".png";
                //没有文件，需要手动创建文件 File还是内存的实例
                //检查文件是否有父目录/文件夹没有了添加 -- 我就直接创建了
                map.put("codeImgName",imgccc); //这里的是我动态生成的部分
                imgccc = imgUri.concat(imgccc);

                System.out.println("图片保存地址为:"+imgccc);
                System.out.println("图片的值为:"+context);
                map.put("imgValue",context.toString());
//                new File(imgccc).createNewFile();
                ImageIO.write(img,"png",new File(imgccc));
                return map;
            }
            catch(IOException e){
                e.printStackTrace();
                System.out.println("IO异常");
            }
        }
        return null;
    }
}
